<template>
  <page-header-wrapper>
    <a-card :bordered="false" style="margin-bottom:11px">
      <a-row size="small">
        <a-button
          type="primary"
          class="title-but"
          @click="onAdd(1)"
          icon="plus">类型</a-button>
      </a-row>
    </a-card>
    <a-card :bordered="false" :bodyStyle="{display: 'flex', justifyContent: 'space-around'}">
      <a-card :loading="status.loading" title="规格列表" style="width: 48%;">
        <a-button
          slot="extra"
          type="link"
          :disabled="checkId.length == 0"
          class="title-but"
          @click="checkSet()"
          :loading="status.showLoading"
        > 批量删除 </a-button>
        <a-directory-tree
          v-if="attrList.length > 0"
          multiple
          @select="onSelect"
          @check="onCheck"
          :checkable="true"
          :defaultExpandAll="false"
          :checkStrictly="true">
          <a-tree-node v-for="(item0, index0) of attrList" :key="index0">
            <span slot="title">
              <span v-if="item0.type == 0" style="color: #4169E1;margin-left: 10px;">
                类型
              </span>
              <span>{{ item0.name }}</span>
            </span>
            <template v-if="item0.children.length > 0">
              <a-tree-node
                v-for="(item1, index1) of item0.children"
                :key="index0+'-'+index1"
                :is-leaf="!item1.children.length > 0" >
                <span slot="title">
                  <span v-if="item1.type == 1" style="color: #00CED1;margin-left: 10px;">
                    规格
                  </span>
                  <span>{{ item1.name }}</span>
                </span>
                <template v-if="item1.children.length > 0">
                  <a-tree-node
                    v-for="(item2, index2) of item1.children"
                    :key="index0+'-'+index1+'-'+index2"
                    is-leaf >
                    <span slot="title">
                      <span v-if="item2.type == 2" style="color: #ddd;margin-left: 10px;">
                        属性
                      </span>
                      <span>{{ item2.name }}</span>
                    </span>
                  </a-tree-node>
                </template>
              </a-tree-node>
            </template>
          </a-tree-node>
        </a-directory-tree>
        <a-empty v-else />
      </a-card>
      <a-affix :offset-top="100" style="width: 48%;">
        <a-card title="编辑规格">
          <a-row size="small" slot="extra">
            <a-button
              v-if="attrInfo.id > 0"
              type="link"
              class="title-but"
              @click="onDel"
              icon="delete">删除</a-button>
            <a-button
              v-if="attrInfo.id > 0 && attrInfo.type < 2"
              type="link"
              class="title-but"
              @click="onAdd(0)"
              icon="plus">添加{{ (attrInfo.type == 0 ? '规格' :'属性') }}</a-button>
          </a-row>
          <a-form
            action=""
            method="post"
            @submit="submitAdd"
            :form="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }">
            <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="父级规格">
              <a-input
                v-decorator="['parent_id']"
                type="number"
                :step="1"/>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="类型">
              <a-input
                v-decorator="['type']"
                type="number"
                :step="1"/>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :hidden="true" :wrapperCol="wrapperCol" label="ID">
              <a-input
                v-decorator="['id', { rules: [ { pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: 'ID格式不正确' } ] } ]"
                type="number"
                :step="1"/>
            </a-form-item>
            <a-form-item
              v-if="attrInfo.parent_name"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="上级规格"
              hasFeedback >
              <a-input
                :disabled="true"
                v-decorator="['parent_name' ]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label=" (attrInfo.type == 0 ? '类型' : (attrInfo.type == 1 ? '规格' : '属性')) + '名称'"
              hasFeedback >
              <a-input
                v-decorator="['name', { rules: [ { required: true, message: '请填写名称' }, { max: 20, message: '名称不能大于20个字符' } ] } ]"
                :placeholder="'请填写' + (attrInfo.type == 0 ? '类型' : (attrInfo.type == 1 ? '规格' : '属性')) + '名称'"/>
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序" help="排序值越小排序越靠前" hasFeedback >
              <a-input
                v-decorator="['sort', { rules: [ { required: false, message: '填写排序' }, { pattern: /((^[1-9]\d*)|^0)(\.\d{0,0}){0,1}$/, message: '排序不对' } ] } ]"
                type="number"
                :step="1"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
              <a-button type="primary" html-type="submit" :loading="status.butLoading">
                保存
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-affix>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { list, save, del, statusAll } from '@/api/goods/attr'
import pick from 'lodash.pick'
import Template from '@/views/diy/Template.vue'

const statusLoading = {
  loading: true,
  butLoading: false, // 提交按钮状态
  delLoading: false, // 删除按钮状态
  showLoading: false
}

export default {
  name: 'AttrList',
  components: {Template},
  data () {
    return {
      attrList: [],
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      attrInfo: {},
      status: statusLoading,
      checkId: [] // 选择中ID
    }
  },
  created () {
    this.getList()
    this.onAdd(1)
  },
  watch: {
    attrInfo (val) {
      this.setDataForm(val)
    }
  },
  methods: {
    getList () {
      list()
        .then(res => {
          this.status.loading = false
          this.attrList = res.data.list
        })
    },
    onSelect (e) {
      this.attrInfo = this.getKeyData(e[0])
    },
    onCheck (e) {
      var checkId = []
      if (e.checked.length > 0) {
        e.checked.forEach(element => {
          var attrInfo = this.getKeyData(element)
          checkId.push(attrInfo.id)
        })
      }
      this.checkId = checkId
      console.log(this.checkId)
    },
    getKeyData (e) {
      var indexArr = typeof e === 'number' ? [e] : e.split('-')
      var attrList = this.attrList
      var attrInfo = {}
      if (indexArr.length === 1) {
        attrInfo = attrList[indexArr[0]]
      } else if (indexArr.length === 2) {
        attrInfo = attrList[indexArr[0]].children[indexArr[1]]
      } else if (indexArr.length === 3) {
        attrInfo = attrList[indexArr[0]].children[indexArr[1]].children[indexArr[2]]
      }
      return attrInfo
    },
    onDel () {
      this.$message.loading({ content: '提交中...', key: 'del' })
      del({ id: this.attrInfo.id }).then(res => {
        this.$message.success({ content: res.msg, key: 'del' })
        if (res.code === 0) {
          this.getList()
          this.onAdd(1)
        }
      })
    },
    /**
     * 批量删除
     */
    checkSet () {
      var that = this
      var text = '删除'
      this.$confirm({
        title: '是否确认' + text + '选中属性?',
        okText: '确认',
        cancelText: '取消',
        onOk () {
          that.$message.loading({ content: '提交中...', key: 'checkSet' })
          statusAll({ id: that.checkId }).then(res => {
            that.$message.success({ content: '提交成功!', key: 'checkSet', duration: 2 })
            that.checkId = []
            that.getList()
          })
        },
        onCancel () {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    submitAdd (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.status.butLoading = true
          save(values).then(res => {
            this.status.butLoading = false
            this.$message.success(res.msg)
            if (res.code === 0) {
              this.getList()
            }
          })
        }
      })
    },
    setDataForm () {
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.attrInfo, ['name', 'sort', 'parent_id', 'id', 'parent_name', 'type']))
      })
    },
    onAdd (isNew = 0) {
      this.attrInfo = {
        id: 0,
        parent_id: this.attrInfo && this.attrInfo.id > 0 && isNew === 0 ? this.attrInfo.id : 0,
        parent_name: this.attrInfo && this.attrInfo.id > 0 && isNew === 0 ? this.attrInfo.name : '顶级类型',
        type: this.attrInfo && this.attrInfo.id > 0 && isNew === 0 ? this.attrInfo.type - 0 + 1 : 0,
        sort: 100,
        name: ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.title-but {
  margin-left: 6px;
}
</style>
